package com.phy.kim.foroffer;

/**
 * @author RiceDoggyRoll
 */
public class Offer001Divide {

  public static void main(String[] args) {
    System.out.println(new Offer001Divide().divide(15, 2));
  }

  public int divide(int a, int b) {
    if (a == Integer.MIN_VALUE && b == -1) {
      return Integer.MAX_VALUE;
    }
    if (a == 0) {
      return 0;
    }
    if (b == 1) {
      return a;
    }
    if (a == b) {
      return 1;
    }
    boolean negFlag = (a > 0) ^ (b > 0) ? true : false;
/*
    将两个数 转为 对应的 负数 做运算
    因为负数的绝对值比正数大1；所以输入给出-2147483648这种坑也可以过
*/
    long dividend = a > 0 ? -a : a;
    long divisor = b > 0 ? -b : b;
    if (dividend > divisor) {
      return 0;
    }
    int result = 0;
    int shift = 31;
    while (dividend <= divisor) {
      while (dividend > divisor << shift) {
        shift--;
        System.out.println(divisor << shift);
      }
      System.out.println("over");
      dividend -= divisor << shift;
      result += 1 << shift;
      System.out.println("result:"+result);
    }
    return negFlag ? - result : result;
  }
}
